<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java_cup.runtime.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="logic.*" %>
    <%@ page import="java.util.List" %>
    <%@ page import="java.util.LinkedList" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
	<%
		ConDiaCClass cdc=Singleton.getInstance();
		Singleton.cleanInstance();
		String input="", output="";
		input=request.getParameter("input");
		Symbol tree=null;
		parser p=null;
		InputStream entrada=null;
		analex analizador;
		FileWriter fichero = null;
        File dir;
		try{
			entrada=new ByteArrayInputStream(input.getBytes("UTF-8"));
			analizador=new analex(entrada);
			p=new parser(analizador);
			tree=p.parse();
			System.out.println("CORRECTO");
		}catch(Exception e){
			System.out.println("ERROR:" + e.toString());
		}
		finally{}
		if(!cdc.getErrores()){
			out.println("<h1>Resultado</h1>");
			
			cdc.runOperations();
			List<String> result=cdc.getRes();
			for(int i=0;i<result.size();i++){
				//out.print("<h3>"+ cdc.getOperations().get(i).toString() +"</h3>");
				output=result.get(i);
				if(!output.startsWith("digraph")){
					out.print("<p>");
					for(int k=0;k<output.length();k++)
						if(output.charAt(k)=='\n')
							out.print("<br>");
						else
							out.print(output.charAt(k));
					out.print("</p>");
				}else{
					String nombre="diagraph"+i;
					String url="/home/jorge/workspace/pl-condiac/WebContent/site/generatedImages/";
					try{
						dir=new File(url);
						dir.mkdir();
						fichero = new FileWriter(url+nombre+".dot");
						fichero.write(output);
						
					}catch (Exception e){
						e.printStackTrace();
					}finally{
						try{
							if (null != fichero)
								fichero.close();
						}catch (Exception e2) {
							e2.printStackTrace();
						}
					}
					
					try{						
						Runtime runtime = Runtime.getRuntime();
					    Process exec = runtime.exec("dot " + url + nombre + ".dot -o " + url + nombre + ".png -Tpng -Gcharset=latin1");
					    
					    out.println("<img src=\"http://localhost:8080/pl-condiac/site/generatedImages/" + nombre + ".png\" style=\"width:600px;\"/>"); 
					    
					}catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
				if(i!=result.size()-1)
					out.print("<br><br>");
			}
		}else{
			out.println("<h1>Errores</h1>");
			List<String> errors=cdc.getErroresOutput();
			for(int i=0;i<errors.size();i++)
				out.println("<p>"+errors.get(i)+"</p>");
		}
		/*out.println(cdc);*/
		
		
	%>
	<!--
	<img src="http://localhost:8080/pl-condiac/site/generatedImages/diagraph0.png" style="width:600px;"/>
	-->
</body>
</html>